package com.zfast.forge.wechat.service;

import com.zfast.forge.wechat.constant.Contants;
import com.zfast.forge.wechat.utils.EncodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public boolean syncWxUserInfo(String res,String openid, String appId) {

        //String 转map
    	//Map wxUserInfo=res==null?new HashMap(): JsonUtils.parse(res, Map.class);
        Map wxUserInfo=new HashMap();
        //将需要存储到数据库的用户信息的nickname进行iso编码
        String nickName=(wxUserInfo.isEmpty())?"":(String) wxUserInfo.get("nickName");
        String isoNickName = EncodeUtil.encodeWxName(nickName);
        wxUserInfo.put("nickName", isoNickName);
        int count = getWxUserExist(openid);
        boolean ret=false;
        //如果数据库中没有该用户信息
        if (count == 0) {
            wxUserInfo.put("appId", appId);
            saveWxUser(wxUserInfo,openid);
            ret=true;
        }
        return ret;
    }

    public int getWxUserExist(String openId) {
        String sql = "select count(1) from T_WX_USER where openid = ? ";
        return jdbcTemplate.queryForObject(sql, Integer.class, openId);
    }

    public void saveWxUser(Map wxUserInfo, String openid) {
        String wxUserId = Contants.getUUID();//t_wx_user主键

        String sql = "insert into T_WX_USER (ID,OPENID,NICKNAME,SEX,CITY,PROVINCE,COUNTRY,HEADIMGURL,UNIONID,LANGUAGE) values " +
                "(?,?,?,?,?,?,?,?,?,?)";

        if(StringUtils.isEmpty(wxUserInfo.get("nickName").toString())){
        	jdbcTemplate.update(sql, wxUserId,openid, "", "", "",
        			"", "", "", "", "");
        }else{
        	jdbcTemplate.update(sql, wxUserId,openid, wxUserInfo.get("nickName"), wxUserInfo.get("gender"), wxUserInfo.get("city"),
                    wxUserInfo.get("province"), wxUserInfo.get("country"), wxUserInfo.get("avatarUrl"), "", wxUserInfo.get("language"));
        }
    }

    /*public IDtoRow getUserInfoByOpenId(String mixId) {
        String sql = "select * from T_WX_USER where OPENID = ? ";
        return jdbcTemplate.query(sql, JdbcTemplateHelper.getDtoRowMapper(), mixId);
    }*/

}
